/**
 * 
 */
package com.ivory.valley.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ivory.valley.common.IvorySession;
import com.ivory.valley.common.IvoryValley;
import com.ivory.valley.common.Resp;
import com.ivory.valley.common.SignAttr;
import com.ivory.valley.dao.TaskDetailsMongo;
import com.ivory.valley.pojo.Task;
import com.ivory.valley.service.TaskService;
import com.ivory.valley.util.DateUtil;
import com.ivory.valley.util.SessionUtil;
import com.mongodb.BasicDBObject;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@RestController
@RequestMapping("/task")
public class TaskController {
	private Log log = LogFactory.getLog(TaskController.class);
	
	@Autowired
	private TaskService taskService;
	
	@Autowired
	private TaskDetailsMongo taskDetailsMongo;
	/**
	 * 发布任务
	 * @param request
	 * @param response
	 * @param TaskUserId
	 * @param keywords
	 * @param taskClassification
	 * @param prepaidBounty
	 * @param deadline
	 * @param taskDetails
	 * @param TaskTime
	 * @return
	 */
	@SuppressWarnings({ "deprecation", "unchecked" })
	@RequestMapping(value="/task.dx")
	public Resp<Object> Task(HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("title") String title,
			@ModelAttribute("value") String deadline,
			@ModelAttribute("contents") String contents,
			@ModelAttribute("address") String address){
		String contextPath = request.getContextPath();
		String servletPath = request.getServletPath();
		log.info("contextPath="+contextPath);
		log.info("servletPath="+servletPath);
		//这里要用到过滤器，拦截未登录的会话
		IvorySession is = SessionUtil.getLogined(request, response);
		String openid = is.getOpenid();
		String task_detail_id = System.currentTimeMillis()+"";
		//拿到media_id保存图片或者音频
		log.info("contents="+contents);
		JSONArray jsonArrayContents = JSONArray.fromObject(contents);
		List<BasicDBObject> dblist = new ArrayList<BasicDBObject>();
		for(int i=0;i<jsonArrayContents.size();i++){
			JSONObject jsonObj = jsonArrayContents.getJSONObject(i);
			String content = jsonObj.getString("contents");
			JSONObject contentObj = JSONObject.fromObject(content);
			String type = contentObj.getString("type");
			String index = contentObj.getString("index");
			String media_id =  null;
			String textContent = "";
			String media_url = "";
			if("1".equals(type)){//文本
				textContent = contentObj.getString("textContent");
			}else if("2".equals(type)){//图片
				media_id = contentObj.getString("media_id");
				media_url = getMedia(media_id,IvoryValley.ConstantAndURL.get_media_url,type,contextPath);
			}else{//音频
				media_id =contentObj.getString("media_id");
				media_url = getMedia(media_id,IvoryValley.ConstantAndURL.get_media_url,type,contextPath);
			}
			log.info("media_url="+media_url);
			BasicDBObject document = new BasicDBObject();
			document.put("type", type);
			document.put("index", index);
			document.put("text_content", textContent);
			document.put("media_url", media_url);
			document.put("task_detail_id", task_detail_id);
			dblist.add(document);
		}
		log.info("dblist="+dblist.toString());
		boolean flag = taskDetailsMongo.insert(dblist);
		log.info("插入mongodb成功");
		Task task = new Task();
		task.setPublish_task_userId(is.getUserId());
		task.setTask_title(title);
		task.setAddress(address);
		task.setReceive_status((byte) 0);
		task.setTask_detail_id(task_detail_id);
		task.setPublish_task_time(Timestamp.valueOf(DateUtil.getCurrentTimeStr()));
		int index = taskService.insertTask(task);
		Resp<Object> resp = new Resp<>();
		if(index>0){
			resp.setSuccessCodeMsg("任务发布成功");
		}else{
			resp.setFailCodeMsg("任务发布失败");
		}
		return resp;
	}
	//获取图片或者影音的二进制文件活其他
	private String getMedia(String media_id,String url,String type,String contextPath) {
		String dir = "";
		String media_url = "";
		try {
			if("2".equals(type)){
				dir = "/picture/"+media_id+".jpg";
			}else{
				dir = "/voice/"+media_id+".speex";
			}
			media_url = "/usr/local/tomcat8.0.0/webapps/ivory-valley/upload"+dir;

			FileOutputStream fos = new FileOutputStream(media_url);
			//BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(media_url));
			url = url.replaceAll("ACCESS_TOKEN", SignAttr.Access_Token).replaceAll("MEDIA_ID", media_id);
			URL urlGet;
			byte[] bytes = null;
			urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			bytes = new byte[size];
			is.read(bytes);
			fos.write(bytes);
			fos.flush();
			fos.close();
			log.info("图片已保存到本地/usr/local/tomcat8.0.0/webapps/ivory-valley/upload");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return media_url;
	}
	/**
	 * @param request
	 * @param response
	 * @param keywords
	 * @param taskClassification
	 * @return
	 */
	@RequestMapping(value="/selectAllTask.dx")
	public Resp<List<Task>> selectAllTask(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("receive_status", 0);
		Resp<List<Task>> resp = taskService.selectAllTask(map);
		log.info("tasklist="+resp.getRes());
		return resp;
	}
	/**
	 * 选择几条任务记录
	 * @param request
	 * @param response
	 * @param receiveTaskUserId
	 * @return
	 */

}
